/*
 * Universidade Federal Fluminense
 * Instituto de Computação
 * Prof. Pedro Braconnot Velloso
 * Sistemas Distribuídos - Turma 2011/2
 * Author: Gabriel Almeida de Oliveira
 * Description: simple threading program for testing and learning purposes
 * compile: gcc -o threads -lpthread threads.c 
 */

#include "const.h"
#include <stdio.h>
#include "server.h"
#include "functions.h"
#include "client.h"
#include <pthread.h>

int main(int argc, char* argv[]){
	
	struct arguments args;
	packet *peers, *me; 
	char errorString[140];
	pthread_t server_thread, client_thread;
	
   //Check for correct Syntax
    if(argc<3) {
    	printf("usage : %s <node to connect> <node name>\n", argv[0]);
    	return ERROR_INVALID_ARGS;
  	}
	
	// Just turned the program on, set our node and send it to the specified host
	
	// allocate and clear allocated memory
	if ( (peers = (packet*) malloc(sizeof(peers)) ) == NULL) {
		snprintf (errorString, sizeof(errorString), "Main: Error allocating Memory");
		DieWithError(errorString);
	}
	memset(peers, 0x0, sizeof(peers));
	

	peers->msg = (char* ) malloc( MAX_MSG_SIZE * sizeof(char) );
	peers->msg = argv[2];

	peers->hash = calculate_hash(argv[2]);
	
	printf("main: peer name hash: %s\n\n", peers->hash);
	peers->address.sin_family = AF_INET;
	peers->address.sin_addr.s_addr = htonl(INADDR_ANY);
	peers->address.sin_port = htons(DEFAULT_PORT);
	
	peers->level = PEER_IN;
	
	me = peers;
	append_node(peers);

	args.hostname = argv[1];
	args.peer_list = peers;

	// create threads: id, inic, function, function parameterss
	pthread_create(&client_thread,NULL,(void* )client, &args);
	pthread_create(&server_thread,NULL,(void* )server, &args.peer_list);
	
	// wait for threads to finish: id, exit status
	pthread_join(client_thread,NULL);
	pthread_join(server_thread,NULL);
	

	// Server left, we need to free memory before exit.
	for(peers=getHead(); peers!=NULL; peers=getHead())
		remove_node(peers);
		
	return 0;
}